package com.huiying.interceptor;


import com.huiying.constant.JwtClaimsConstant;
import com.huiying.context.BaseContext;
import com.huiying.properties.JwtProperties;
import com.huiying.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //如果令牌为空，直接拒绝
        if (!StringUtils.hasText(token)) {
            log.warn("请求头中无令牌，访问被拒绝");
            response.setStatus(401);
            return false;
        }

        Long userId;
        try {
            //尝试解析令牌，如果失败（过期、伪造等），则捕获异常
            log.info("开始校验JWT令牌: {}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("从令牌中解析出用户ID: {}", userId);

        } catch (ExpiredJwtException e) {
            log.warn("令牌已过期: {}", token);
            response.setStatus(401); // 明确告知前端token过期
            return false;
        } catch (Exception e) {
            log.error("令牌解析失败: {}", token, e);
            response.setStatus(401); // 明确告知前端token无效
            return false;
        }

        // 从Redis中验证令牌是否有效
        String tokenKey = "user:token:" + userId;
        String redisToken = redisTemplate.opsForValue().get(tokenKey);
        if (redisToken == null || !redisToken.equals(token)) {
            log.warn("令牌与Redis中存储的不一致，可能已在别处登录或已注销");
            response.setStatus(401);
            return false;
        }

        // 校验通过，刷新Redis中的令牌有效期 (续期)
        redisTemplate.expire(tokenKey, jwtProperties.getUserTtl(), TimeUnit.SECONDS);
        log.info("用户 {} 的令牌有效期已刷新", userId);

        //将用户ID存入线程本地变量，供后续业务使用
        BaseContext.setCurrentId(userId);

        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理线程本地变量，防止内存泄漏
        BaseContext.removeCurrentId();
    }
}
